<template>
  <div :class="prefixCls">
    <Image v-if="signInfo" width="72px" height="32px" :src="signInfo.url" />
    <a-button v-else @click="handleClick">电子签名</a-button>
    <BasicModal
      destoryOnClose
      width="30%"
      @register="registerModal"
      title="签名验证"
      @ok="handleSubmit"
    >
      <div class="flex flex-col items-center">
        <QrCode
          :value="qrUrl"
          :options="{
            color: { dark: '#2B63A1' },
          }"
        />
        <p class="text-center">请使用微信扫描二维码</p>
        <a-button @click="handleSubmit">确定</a-button>
      </div>
    </BasicModal>
  </div>
</template>

<script lang="ts" setup name="SignatureModal">
  import { type PropType, onMounted, ref, computed } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import QueryString from 'qs';
  import { QrCode } from '/@/components/Qrcode/index';
  import { Image } from 'ant-design-vue';
  import { useDesign } from '/@/hooks/web/useDesign';
  import { useIntervalFn } from '@vueuse/core';
  import { WorkItemSignInfoApi } from '/@/api/flow/flow';
  import { useMessage } from '/@/hooks/web/useMessage';

  const { prefixCls } = useDesign('SignatureModal');
  const { createMessage } = useMessage();

  const props = defineProps({
    value: {
      type: Object as PropType<Indexable>,
    },
    url: { type: String },
    guid: { type: String },
  });
  const emit = defineEmits(['update:value']);
  const qrUrl = computed(() => {
    const { guid, url } = props;
    const p = QueryString.stringify({ guid }, { addQueryPrefix: true });

    return url + p;
  });
  const [registerModal, { setModalProps, closeModal, changeLoading }] = useModalInner();
  let timerFn;
  let signInfo = ref<Indexable | null>();
  const getSignatureInfo = async () => {
    try {
      const ret = await WorkItemSignInfoApi(props.guid || '');

      ret && (signInfo.value = ret.sign);
      close();
    } catch (error) {
      timerFn && timerFn.pause();
    }
  };
  const handleClick = async () => {
    timerFn && timerFn.pause();

    changeLoading(true);

    setModalProps({
      open: true,
      loading: false,
      canFullscreen: false,
      footer: null,
      closable: false,
      centered: false,
    });
    timerFn = useIntervalFn(getSignatureInfo, 15 * 1000);
  };
  const handleSubmit = async () => {
    await getSignatureInfo();
    if (signInfo.value) {
      emit('update:value', { sign: signInfo.value });
    }
    closeModal();
  };
  function close(flag = false) {
    if (signInfo.value) {
      closeModal();
      emit('update:value', { sign: signInfo.value });

      timerFn && timerFn.pause();
      return;
    }
    if (flag) {
      createMessage.warning('请使用微信扫描二维码签名');
    }
  }
  onMounted(() => {});
</script>
<style lang="less" scoped></style>
